<!-- 群组 -->
<template>
	<view v-if="!loading.init">
		<template v-if="isTeacher">
			<view class="uv-flex-row">
				<uv-button text="新建群组" custom-style="width: 100px;height: 50px;" @click="groupNamePopupRef.open('create')"></uv-button>
				<navigator url="/pages/custom-course/custom-course" style="height: 35px;border: 1px solid #fff;border-radius: 10px;line-height: 35px;text-align: center;padding: 0 10px;">自定义课程</navigator>
			</view>
		</template>
		<template v-else>
			<view class="uv-flex-row">
				<uv-button text="加入群组" custom-style="width: 100px;height: 50px;" @click="applyPopupRef.open()"></uv-button>
				<navigator url="/pages/report/report" style="height: 35px;border: 1px solid #fff;border-radius: 10px;line-height: 35px;text-align: center;padding: 0 10px;">成绩报告</navigator>
			</view>
		</template>
		<template v-if="groupData.list.length">
			<view class="side-list">
				<view @click="goToGroup(item)" class="item uv-flex-row" v-for="(item,index) in groupData.list" :key="index"
					style="width: 240px;height: 48px;line-height: 48px;justify-content: center;align-items: center;border: 1px solid red;text-align: center;border-radius: 5px;cursor: pointer;">
					<uv-avatar :src="item.logo" size="24px" custom-style="margin-right: 10px;"></uv-avatar>{{item.groupName}}
				</view>
			</view>
			<view class="content" style="background: #1F2128;width: 1000px;height: 800px;margin: 30px auto;border-radius: 10px;position: relative;">
				<view class="hd uv-flex-row" style="align-items: center;">
					<uv-avatar :src="groupDetail.logo" size="60px"></uv-avatar>
					<view style="margin: 0 10px;">
						<uv-text :text="`群号：${groupDetail.groupCode}`" color="#fff"></uv-text>
						<view class="name uv-flex-row" style="align-items: center;">
							<text style="color: #fff;font-size: 20px;font-weight: 700;margin-top: 5px;">{{groupDetail.groupName}}</text>
							<template v-if="isManager">
								<uv-icon name="edit-pen" color="#fff" size="24px" @click="groupNamePopupRef.open('change')"></uv-icon>
								<uv-icon name="trash" color="#fff" size="24px" @click="delGroup"></uv-icon>
							</template>
						</view>
					</view>
					<template v-if="isManager">
						<uv-button @click="openApplyList" :text="`入群申请${groupData.applyList.length}`" style="margin: 0 10px;" v-if="groupData.applyList.length"></uv-button>
						<uv-button text="添加课程包" style="margin: 0 10px;" @click="chpaterPopupRef.open()"></uv-button>
						<uv-button text="邀请成员" @click="inviteUser"></uv-button>
					</template>
					<template v-else>
						<uv-button text="退出群组" type="error" @click="exitGroup"></uv-button>
					</template>
				</view>
				<view>
					<uv-text text="学习目标：" color="#fff"></uv-text>
					<uv-text :text="`正确WPM(字/分钟):${groupDetail.successWpm}`" color="#fff"></uv-text>
					<uv-text :text="`WPM(字/分钟):${groupDetail.wpm}`" color="#fff"></uv-text>
					<uv-text :text="`KPM(键/分钟):${groupDetail.kpm}`" color="#fff"></uv-text>
					<uv-text :text="`准确率(%):${groupDetail.accuracy}`" color="#fff"></uv-text>
					<uv-text :text="`按键准确率(%):${groupDetail.accuracyKpm}`" color="#fff"></uv-text>
					<uv-text :text="`练习时长(小时):${groupDetail.learningTime}`" color="#fff"></uv-text>
				</view>
				<template v-if="isActivated">
					<view style="margin: 30px;">
						<uv-subsection :list="list" :current="current" @change="change"></uv-subsection>
						<view>
							<view class="item uv-flex-row" v-for="(item,index) in groupData.members" :key="index">
								<span style="color:#fff;margin: 10px;">{{item.nickname}}</span>
								<span v-if="item.characterId === myCharacterId" style="color:#fff;margin: 10px;width: 20px;height: 20px;line-height: 20px;text-align:center;border: 1px solid red;color: red;">我</span>
								<uv-avatar :src="`/static/images/character/${item.avatar}-small.png`" size="40px" mode="aspectFill"></uv-avatar>
								<span style="color:#fff;margin: 10px;">正确wpm：{{item.successWpm}}</span>
								<span style="color:#fff;margin: 10px;">wpm：{{item.wpm}}</span>
								<span style="color:#fff;margin: 10px;">kpm：{{item.kpm}}</span>
								<span style="color:#fff;margin: 10px;">准确率：{{item.accuracy}}%</span>
								<span style="color:#fff;margin: 10px;">按键准确率：{{item.accuracyKey}}%</span>
								<template v-if="isManager">
									<span style="color:#fff;margin: 10px;cursor: pointer;">查看详情</span>
									<span style="color:#fff;margin: 10px 0;">|</span>
									<span style="color:#fff;margin: 10px;cursor: pointer;" @click="delMember(item)">移除</span>
								</template>
							</view>
						</view>
					</view>
					<view style="padding: 30px 0;">
						<uv-text text="群组课程包" color="#fff" size="18px" align="left"></uv-text>
						<view class="list uv-flex-row">
							<view class="item" style="margin: 10px;position: relative;" v-for="(item,index) in groupData.groupChpaterList" :key="index">
								<image :src="item.logo.path || item.logo" mode="aspectFill" style="width: 100px;height: 100px;border-radius: 10px;"></image>
								<uv-text :text="`练习次数：${item.totalLearnCount?item.totalLearnCount:0}`" color="#fff" size="12px"></uv-text>
								<view v-if="isManager" style="position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);z-index: 1;">
									<uv-button type="error" text="删除" custom-style="height: 30px;" @click="removeChapter(item)"></uv-button>
								</view>
								<view v-else style="position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);z-index: 1;">
									<navigator :url="`/pages/map/map?chapter=${item.chapter}`" style="color: #fff;font-size: 12px;">立即学习</navigator>
								</view>
							</view>
							<view v-if="isManager && groupData.groupChpaterList.length!=chapterListAll.length" @click="chpaterPopupRef.open()" class="uv-flex-row"
								style="width: 100px;height: 100px;border: 1px dashed red;margin: 10px;border-radius: 10px;cursor: pointer;justify-content: center;align-items: center;">
								<uv-icon name="plus" color="#666"></uv-icon>
							</view>
						</view>
					</view>
				</template>
				<template v-else-if="!isManager">
					<view style="position: absolute;z-index: 2;right: 0;" class="uv-flex-row">
						<uv-button text="删除记录" @click="removeApply"></uv-button>
						<uv-button text="再次申请" @click="againApply"></uv-button>
					</view>
					<view v-if="groupDetail.applyStatus == 'APPLYING'"
						style="position: absolute;left: 0;right: 0;top: 0;bottom: 0;z-index: 1;background-color: rgba(0, 0, 0, 0.5);color: #fff;font-size: 40px;display: flex;align-items: center;justify-content: center;">
						申请中
					</view>
					<view v-if="groupDetail.applyStatus == 'REFUSE'"
						style="position: absolute;left: 0;right: 0;top: 0;bottom: 0;z-index: 1;background-color: rgba(0, 0, 0, 0.5);color: red;font-size: 40px;display: flex;align-items: center;justify-content: center;">
						已拒绝
					</view>
				</template>
				<template v-else>
					<view class="un-actived" style="position: absolute;left: 0;top: 0;right: 0;bottom: 0;background: rgba(0, 0, 0, 0.8);">
						<uv-text text="群组功能已激活" color="#fff" size="18px" align="center"></uv-text>
						<uv-text text="默认已创建，开始邀请成员加入吧~" color="#fff" size="22px" align="center"></uv-text>
						<uv-button text="开始邀请成员" @click="invite" :loading="loading.invite" :throttle-time="200"></uv-button>
					</view>
				</template>
			</view>
			<apply-list-popup :list="groupData.applyList" ref="applyListPopupRef" @reload="getApplyList();reloadData()" />
			<chapter-popup ref="chpaterPopupRef" :groupCode="groupDetail.groupCode" :selectChapterList="groupData.groupChpaterList" :chapterList="chapterListAll" @reloadData="reloadData" />
		</template>
		<template v-else-if="isTeacher">
			<uv-empty text="暂无群组~ 新建群组开始管理您的成员"></uv-empty>
			<uv-button text="创建群组" @click="groupNamePopupRef.open('create')"></uv-button>
		</template>
		<template v-else>
			<uv-empty text="暂无群组~ 加入群组和大家一起练习打字吧"></uv-empty>
			<uv-button text="加入群组" @click="applyPopupRef.open()"></uv-button>
		</template>
		<apply-popup ref="applyPopupRef" @reload="init" />
		<group-name-popup :group-name="groupDetail.groupName" ref="groupNamePopupRef" @confirm="confirmGroupName" />
	</view>
</template>
<script setup>
	import { watchEffect } from 'vue';
	// 监听推送的消息
	uni.onPushMessage((res) => {
		console.log(res)
		if (res.data.payload?.groupCode == groupData.activeCode) {
			switch (res.data.payload?.type) {
				case 'GROUP_APPLY': //有人申请时触发
					getApplyList();
					break;
				case 'GROUP_APPLY_CHANGE': //同意/拒绝后触发
					init();
					break;
			}
		}
	})
	import { addUrlParameter, removeUrlParameter } from '@/common/utils/index.js';
	import { onLoad } from '@dcloudio/uni-app';
	import { computed, reactive, ref, watch, defineComponent } from 'vue';
	import { chapterList } from '@/common/api/list.js';
	import { groupList, groupCreate, groupChange, groupMembers, groupChpaterList, groupMemberDelete, groupRemove, groupMemberExit, groupExitApply, groupApplyCreate } from '@/common/api/group.js';
	import { getLastDaysTime } from '@/common/utils/index.js';
	import applyListPopup from './components/apply-list-popup.vue';
	import applyPopup from './components/apply-popup.vue';
	import chapterPopup from './components/chapter-popup.vue';
	import groupNamePopup from './components/group-name-popup.vue';
	import { checkLocalCharacter } from '@/common/js/character.js';
	defineComponent({ applyPopup, applyListPopup, chapterPopup, groupNamePopup });
	const db = uniCloud.database();
	const applyListPopupRef = ref(null);
	const applyPopupRef = ref(null);
	const chpaterPopupRef = ref(null);
	const groupNamePopupRef = ref(null);
	const list = ref(['今天', '过去7天', '过去30天']);
	const current = ref(0);
	try {
		// checkLocalCharacter();
		onLoad(async (options) => {
			if (options.id) {
				groupData.activeCode = options.id;
				getDetail();
			}
			init();
		})
	} catch (e) {}

	const groupData = reactive({
		list: [],
		activeIndex: 0,
		activeCode: '',
		groupChpaterList: [],
		applyList: [],
		members: []
	});
	let groupDetail = reactive({});
	const loading = reactive({
		init: true,
		invite: false
	})

	function reloadData() {
		getGroupChapter();
		getGroupMembers();
	}
	const myCharacterId = computed(() => {
		return getApp().globalData.dzcharacter?.character?.characterId;
	})
	const isTeacher = computed(() => {
		return getApp().globalData.dzcharacter?.character?.type === 'TEACHER';
	})
	const isManager = computed(() => {
		return groupDetail.characterId === myCharacterId.value;
	})
	// 是否激活状态
	const isActivated = computed(() => {
		const isMember = !isManager.value && groupDetail.applyStatus === 'AGREE' || isManager.value;
		return groupDetail.status === 'ACTIVATED' && isMember;
	})
	watchEffect(() => {
		if (isActivated.value) {
			getGroupChapter();
			getApplyList();
			getGroupMembers();
		}
	})
	const chapterListAll = computed(() => {
		const _list = getApp().globalData.dzdata?.chapterList;
		if (!_list) {
			getAllChapterList();
		}
		return _list ? _list : [];
	})
	async function init() {
		const characterId = getApp().globalData.dzcharacter?.character?.characterId;
		const { data } = await groupList({ characterId });
		console.log('data===>', data)
		groupData.list = data;
		const findIndex = groupData.list.findIndex(item => item.groupCode === groupData.activeCode);
		groupData.activeIndex = findIndex > -1 ? findIndex : 0;
		if (groupData.list.length) {
			groupDetail = Object.assign(groupDetail, groupData.list[groupData.activeIndex]);
			groupData.activeCode = groupDetail.groupCode;
			await getDetail();
			addUrlParameter('id', groupData.activeCode);
		} else {
			removeUrlParameter('id');
		}
		loading.init = false;
	}

	function goToGroup(item) {
		uni.$uv.route({
			url: '/group',
			params: {
				id: item.groupCode
			}
		})
	}
	// 获取群组详情
	async function getDetail() {
		const characterId = getApp().globalData.dzcharacter?.character?.characterId;
		if (!characterId || !groupData.activeCode) {
			throw new Error('非法请求');
		}
		const { result } = await db.collection('a-dz-group-list').where(`groupCode == "${groupData.activeCode}"`).field('accuracy,accuracyKpm,characterId,createdTime,groupCode,groupName,kpm,learningTime,logo,status,successWpm,wpm').get();
		if (result.data.length) {
			groupDetail = Object.assign(groupDetail, result.data[0]);
		}
	}

	function getTime() {
		switch (current.value) {
			case 0:
				return getLastDaysTime(0);
			case 1:
				return getLastDaysTime(7);
			case 2:
				return getLastDaysTime(30);
		}
	}

	function change(index) {
		current.value = index;
		getGroupMembers();
	}
	// 获取群组成员列表
	async function getGroupMembers() {
		const { data } = await groupMembers({
			groupCode: groupDetail.groupCode,
			...getTime()
		})
		groupData.members = data;
	}
	// 获取邀请列表
	async function getApplyList() {
		const { result } = await db.collection('a-dz-group-apply-list').where(`groupCode == "${groupData.activeCode}" && applyStatus != "REFUSE" && applyStatus != "AGREE"`).get();
		groupData.applyList = result.data;
	}
	// 打开邀请列表
	function openApplyList() {
		getApplyList();
		applyListPopupRef.value.open();
	}
	// 开始邀请
	async function invite() {
		const characterId = getApp().globalData.dzcharacter?.character?.characterId;
		loading.invite = true;
		await groupChange({
			groupCode: groupDetail.groupCode,
			characterId,
			params: {
				status: 'ACTIVATED'
			}
		})
		groupDetail.status = 'ACTIVATED';
		loading.invite = false;
		getDetail();
		inviteUser();
	}
	// 获取完整数据
	async function getAllChapterList() {
		const { data } = await chapterList({ uid: uniCloud.getCurrentUserInfo().uid });
		getApp().globalData.setdzdata('chapterList', data);
	}
	// 获取群组的章节
	async function getGroupChapter() {
		const { data } = await groupChpaterList({
			groupCode: groupData.activeCode
		})
		groupData.groupChpaterList = data;
	}
	// 确认名称
	async function confirmGroupName({ groupName, type } = {}) {
		const characterId = getApp().globalData.dzcharacter?.character?.characterId;
		switch (type) {
			case 'create':
				await groupCreate({
					characterId,
					groupName,
					uid: uniCloud.getCurrentUserInfo().uid
				});
				init();
				break;
			case 'change':
				await groupChange({
					groupCode: groupDetail.groupCode,
					characterId,
					params: {
						groupName
					}
				})
				getDetail();
				break;
		}
	}
	// 删除课程
	function removeChapter(item) {
		uni.showModal({
			content: '确认群组删除该课程？',
			success(res) {
				if (res.confirm) {
					chpaterPopupRef.value.removeOnlyOne(item.chapter);
				}
			}
		})
	}
	// 邀请其他人
	function inviteUser() {
		uni.showModal({
			content: `邀请链接：${location.host}/group/invite?id=${groupDetail.groupCode}；邀请码：${groupDetail.groupCode}`,
			success(res) {
				if (res.confirm) {
					uni.setClipboardData({
						data: `${location.host}/group/invite?id=${groupDetail.groupCode}`
					})
				}
			}
		})
	}

	function delGroup() {
		uni.showModal({
			title: '解散群组',
			content: `您确定解散「${groupDetail.groupName}」吗？解散后群组内的数据都将被清除，并无法恢复`,
			success(res) {
				if (res.confirm) {
					const characterId = getApp().globalData.dzcharacter?.character?.characterId;
					groupRemove({
						characterId,
						groupCode: groupDetail.groupCode
					}).then(res2 => {
						init();
					})
				}
			}
		})
	}

	function delMember(item) {
		uni.showModal({
			title: '移除成员',
			content: `您确定将「${item.nickname}」移除群组吗？移除后该用户将无法查看群的信息和练习课程包`,
			success(res) {
				if (res.confirm) {
					groupMemberDelete({ characterId: myCharacterId.value, memberUid: item.uid, groupCode: groupDetail.groupCode }).then(res => {
						getGroupMembers();
					})
				}
			}
		})
	}

	function exitGroup() {
		uni.showModal({
			title: '退出群组',
			content: `您确定退出「${groupDetail.groupName}」吗？退出后将无法查看群组信息并练习群组自定义课程`,
			success(res) {
				if (res.confirm) {
					groupMemberExit({
						characterId: myCharacterId.value,
						groupCode: groupDetail.groupCode
					}).then(res => {
						init();
					})
				}
			}
		})
	}
	async function removeApply() {
		await groupExitApply({
			characterId: myCharacterId.value,
			groupCode: groupDetail.groupCode
		})
		init();
	}
	async function againApply() {
		await groupApplyCreate({
			characterId: myCharacterId.value,
			groupCode: groupDetail.groupCode
		})
		init();
	}
</script>
<style>
</style>